<template>
  <div class="project-manager">
    <n-card title="项目管理示例">
      <n-space vertical>
        <!-- 创建项目 -->
        <n-card title="创建项目" size="small">
          <n-form inline>
            <n-form-item label="项目名称">
              <n-input v-model:value="newProjectName" placeholder="输入项目名称" />
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="handleCreateProject" :loading="creating">
                创建项目
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>

        <!-- 项目列表 -->
        <n-card title="项目列表" size="small">
          <n-space vertical>
            <n-button @click="handleLoadProjects" :loading="loading">
              刷新项目列表
            </n-button>
            
            <n-list v-if="projects.length > 0">
              <n-list-item v-for="project in projects" :key="project.id">
                <n-thing :title="project.name" :description="project.description">
                  <template #header-extra>
                    <n-space>
                      <n-button size="small" @click="handleOpenProject(project)">
                        打开
                      </n-button>
                      <n-button size="small" @click="handleSaveProject(project)">
                        保存
                      </n-button>
                      <n-button size="small" type="error" @click="handleDeleteProject(project)">
                        删除
                      </n-button>
                    </n-space>
                  </template>
                  <div>
                    <p>ID: {{ project.id }}</p>
                    <p>创建时间: {{ project.createdAt }}</p>
                    <p>分辨率: {{ project.resolution?.width }}x{{ project.resolution?.height }}</p>
                  </div>
                </n-thing>
              </n-list-item>
            </n-list>
            
            <n-empty v-else description="暂无项目" />
          </n-space>
        </n-card>

        <!-- 导出项目 -->
        <n-card title="导出项目" size="small">
          <n-form inline>
            <n-form-item label="项目ID">
              <n-input v-model:value="exportProjectId" placeholder="输入项目ID" />
            </n-form-item>
            <n-form-item label="格式">
              <n-select 
                v-model:value="exportFormat" 
                :options="formatOptions" 
                style="width: 120px"
              />
            </n-form-item>
            <n-form-item>
              <n-button @click="handleExportProject" :loading="exporting">
                导出
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>

        <!-- 操作日志 -->
        <n-card title="操作日志" size="small">
          <n-scrollbar style="max-height: 200px">
            <n-list>
              <n-list-item v-for="(log, index) in logs" :key="index">
                <n-text :type="log.type">{{ log.message }}</n-text>
                <template #suffix>
                  <n-text depth="3">{{ log.time }}</n-text>
                </template>
              </n-list-item>
            </n-list>
          </n-scrollbar>
        </n-card>
      </n-space>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NSpace,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NList,
  NListItem,
  NThing,
  NEmpty,
  NSelect,
  NScrollbar,
  NText
} from 'naive-ui'
import { projectService, type ProjectData } from '../services/project.service'

const message = useMessage()

// 状态管理
const loading = ref(false)
const creating = ref(false)
const exporting = ref(false)
const projects = ref<ProjectData[]>([])

// 表单数据
const newProjectName = ref('')
const exportProjectId = ref('')
const exportFormat = ref<'mp4' | 'gif' | 'webm'>('mp4')

// 格式选项
const formatOptions = [
  { label: 'MP4', value: 'mp4' },
  { label: 'GIF', value: 'gif' },
  { label: 'WebM', value: 'webm' }
]

// 操作日志
const logs = ref<Array<{ message: string; type: 'success' | 'error' | 'info'; time: string }>>([])

// 添加日志
function addLog(message: string, type: 'success' | 'error' | 'info' = 'info') {
  logs.value.unshift({
    message,
    type,
    time: new Date().toLocaleTimeString()
  })
  
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

// 加载项目列表
async function handleLoadProjects() {
  loading.value = true
  addLog('开始加载项目列表...')
  
  try {
    const result = await projectService.getAllProjects()
    
    if (result.success && result.data) {
      projects.value = result.data
      addLog(`成功加载 ${result.data.length} 个项目`, 'success')
      message.success(result.message || '项目列表加载成功')
    } else {
      addLog(`加载项目列表失败: ${result.error?.message}`, 'error')
      message.error(result.error?.message || '加载项目列表失败')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`加载项目列表异常: ${errorMsg}`, 'error')
    message.error('加载项目列表失败')
  } finally {
    loading.value = false
  }
}

// 创建项目
async function handleCreateProject() {
  if (!newProjectName.value.trim()) {
    message.warning('请输入项目名称')
    return
  }

  creating.value = true
  addLog(`开始创建项目: ${newProjectName.value}`)
  
  try {
    const result = await projectService.createProject({
      name: newProjectName.value.trim(),
      description: '通过项目管理器创建的项目'
    })
    
    if (result.success && result.data) {
      addLog(`项目创建成功: ${result.data.name} (ID: ${result.data.id})`, 'success')
      message.success(result.message || '项目创建成功')
      
      // 清空表单
      newProjectName.value = ''
      
      // 刷新项目列表
      await handleLoadProjects()
    } else {
      addLog(`项目创建失败: ${result.error?.message}`, 'error')
      message.error(result.error?.message || '项目创建失败')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`项目创建异常: ${errorMsg}`, 'error')
    message.error('项目创建失败')
  } finally {
    creating.value = false
  }
}

// 打开项目
async function handleOpenProject(project: ProjectData) {
  addLog(`打开项目: ${project.name}`)
  
  try {
    const result = await projectService.updateProjectLastOpened(project.id!)
    
    if (result.success) {
      addLog(`项目最后打开时间已更新: ${project.name}`, 'success')
      message.success('项目已打开')
    } else {
      addLog(`更新最后打开时间失败: ${result.error?.message}`, 'error')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`打开项目异常: ${errorMsg}`, 'error')
  }
}

// 保存项目
async function handleSaveProject(project: ProjectData) {
  addLog(`保存项目: ${project.name}`)
  
  try {
    const result = await projectService.saveProject(project.id!, {
      description: `${project.description || ''} (已保存于 ${new Date().toLocaleString()})`
    })
    
    if (result.success) {
      addLog(`项目保存成功: ${project.name}`, 'success')
      message.success('项目保存成功')
      
      // 刷新项目列表
      await handleLoadProjects()
    } else {
      addLog(`项目保存失败: ${result.error?.message}`, 'error')
      message.error(result.error?.message || '项目保存失败')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`项目保存异常: ${errorMsg}`, 'error')
    message.error('项目保存失败')
  }
}

// 删除项目
async function handleDeleteProject(project: ProjectData) {
  addLog(`删除项目: ${project.name}`)
  
  try {
    const result = await projectService.deleteProject(project.id!)
    
    if (result.success) {
      addLog(`项目删除成功: ${project.name}`, 'success')
      message.success('项目删除成功')
      
      // 刷新项目列表
      await handleLoadProjects()
    } else {
      addLog(`项目删除失败: ${result.error?.message}`, 'error')
      message.error(result.error?.message || '项目删除失败')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`项目删除异常: ${errorMsg}`, 'error')
    message.error('项目删除失败')
  }
}

// 导出项目
async function handleExportProject() {
  if (!exportProjectId.value.trim()) {
    message.warning('请输入项目ID')
    return
  }

  exporting.value = true
  addLog(`开始导出项目: ${exportProjectId.value} (格式: ${exportFormat.value})`)
  
  try {
    const result = await projectService.exportProject({
      id: exportProjectId.value.trim(),
      format: exportFormat.value
    })
    
    if (result.success && result.data) {
      addLog(`项目导出成功: ${result.data.path}`, 'success')
      message.success(`项目导出成功: ${result.data.path}`)
    } else {
      addLog(`项目导出失败: ${result.error?.message}`, 'error')
      message.error(result.error?.message || '项目导出失败')
    }
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    addLog(`项目导出异常: ${errorMsg}`, 'error')
    message.error('项目导出失败')
  } finally {
    exporting.value = false
  }
}

// 组件挂载时加载项目列表
onMounted(() => {
  addLog('项目管理器已初始化')
  handleLoadProjects()
})
</script>

<style lang="scss" scoped>
.project-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
</style>
